package com.songqintuan.platform.security;

import java.io.Serializable;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.SelectItem;

import net.sf.cglib.beans.BeanCopier;

import com.songqintuan.common.util.MessageFactory;
import com.songqintuan.common.util.SpringFacesUtil;
import com.songqintuan.common.util.ValidatorUtil;
import com.songqintuan.model.po.AuthorityRole;
import com.songqintuan.model.po.SystemUser;
import com.songqintuan.model.po.UserRole;
import com.songqintuan.model.vo.SystemUserVo;
import com.songqintuan.persist.service.hibernate.IAuthorityRoleService;
import com.songqintuan.persist.service.hibernate.ISystemUserService;
import com.songqintuan.persist.service.hibernate.IUserRoleService;
import com.songqintuan.platform.base.IManagePojoPageBean;
import com.songqintuan.platform.base.ManagePojoPageBean;
import com.songqintuan.platform.common.constant.PlatformConstants;
import com.songqintuan.platform.common.constant.PlatformSpringBeanConstants;
import com.songqintuan.platform.page.SystemUserPage;
import com.songqintuan.platform.tree.ResourceTree;
import com.songqintuan.platform.util.EntityDataUtil;

import freemarker.template.utility.StringUtil;



@ManagedBean(name="manageSystemUserPage")
@SessionScoped
public class ManageSystemUserPageBean extends ManagePojoPageBean implements IManagePojoPageBean, Serializable {

	private static final long serialVersionUID = 5054087821033164829L;
	
	private SystemUserPage page;
	
	private SystemUserVo view;
	private SystemUserVo edit;
	
	//分配权限
	private String currentUserId;
	private String currentLoginName;
	private String[] roles = null;
	private SelectItem[] allRoles = null;

	public SystemUserPage getPage() {
		return page;
	}

	public void setPage(SystemUserPage page) {
		this.page = page;
	}

	public SystemUserVo getView() {
		return view;
	}

	public void setView(SystemUserVo view) {
		this.view = view;
	}

	public SystemUserVo getEdit() {
		return edit;
	}

	public void setEdit(SystemUserVo edit) {
		this.edit = edit;
	}

	public String getCurrentUserId() {
		return currentUserId;
	}

	public void setCurrentUserId(String currentUserId) {
		this.currentUserId = currentUserId;
	}

	public String getCurrentLoginName() {
		return currentLoginName;
	}

	public void setCurrentLoginName(String currentLoginName) {
		this.currentLoginName = currentLoginName;
	}

	public String[] getRoles() {
		return roles;
	}

	public void setRoles(String[] roles) {
		this.roles = roles;
	}

	public SelectItem[] getAllRoles() {
		return allRoles;
	}

	public void setAllRoles(SelectItem[] allRoles) {
		this.allRoles = allRoles;
	}

	public ManageSystemUserPageBean(){
		
		SystemUser obj = new SystemUser();
		page = new SystemUserPage(1,PlatformConstants.DEFAULT_ONE_PAGE_NUMBER,obj);
		page.getPageDatas();

	}

	public String selectPageNo() {
		String result = null;
		String pageNo = (String) SpringFacesUtil.getRequestParameter("pageNo");
		if (null != this.getPage().getPageNo()) {
			if (this.getPage().getPageNo().intValue() == Integer.valueOf(pageNo).intValue()) {
				return result;
			}
		}
		this.getPage().setPageNo(Integer.valueOf(pageNo).intValue());
		this.getPage().getPageDatas();
		return result;
		
	}
	public String viewAction(){
		String result = null;
		clearErrorMessages();
		ISystemUserService<SystemUser,String> objService = (ISystemUserService<SystemUser,String>)SpringFacesUtil.getSpringBean(PlatformSpringBeanConstants.SYSTEM_USER_SERVICE_BEAN_NAME);
		objService.setEntityClass(SystemUser.class);
		objService.setPKClass(String.class);
		String objId= (String) SpringFacesUtil.getRequestParameter("objId");
		SystemUser obj = objService.findById(objId);
		SystemUserVo objVo =new SystemUserVo();
		BeanCopier copyHere = BeanCopier.create(SystemUser.class, SystemUserVo.class, false);
		copyHere.copy(obj, objVo, null);
		this.setAction(PlatformConstants.ACTION_VIEW_TYPE);
		this.setView(objVo);
		return result;
	}
	public String editAction(){//get data
		String result = null;
		clearErrorMessages();
		ISystemUserService<SystemUser,String> objService = (ISystemUserService<SystemUser,String>)SpringFacesUtil.getSpringBean(PlatformSpringBeanConstants.SYSTEM_USER_SERVICE_BEAN_NAME);
		objService.setEntityClass(SystemUser.class);
		objService.setPKClass(String.class);
		String objId= (String) SpringFacesUtil.getRequestParameter("objId");
		SystemUser obj = objService.findById(objId);
		SystemUserVo objVo =new SystemUserVo();
		BeanCopier copyHere = BeanCopier.create(SystemUser.class, SystemUserVo.class, false);
		copyHere.copy(obj, objVo, null);
		this.setAction(PlatformConstants.ACTION_EDIT_TYPE);
		this.setEdit(objVo);
		return result;
	}
	public String viewToEditAction() {
		String result = null;
		clearErrorMessages();
		this.setEdit(this.getView());
		this.setView(null);
		this.setAction(PlatformConstants.ACTION_EDIT_TYPE);
		return result;
	}
	public String updateAction(){
		String result = null;
		try {
			this.clearErrorMessages();
			validator(this.getErrorMessages(),this.getEdit());
			if (!(this.getErrorMessages().isEmpty())) {
				return null;
			}
			ISystemUserService<SystemUser,String> objService = (ISystemUserService<SystemUser,String>)SpringFacesUtil.getSpringBean(PlatformSpringBeanConstants.SYSTEM_USER_SERVICE_BEAN_NAME);
			objService.setEntityClass(SystemUser.class);
			objService.setPKClass(String.class);
			SystemUser obj = objService.findById(this.getEdit().getId());
			obj.setUserName(this.getEdit().getUserName());
			obj.setSex(this.getEdit().getSex());
			obj.setLoginPassword(this.getEdit().getLoginPassword());
			obj.setMobile(this.getEdit().getMobile());
			obj.setPhone(this.getEdit().getPhone());
			obj.setEmail(this.getEdit().getEmail());
			obj.setQicq(this.getEdit().getQicq());
			obj.setMsn(this.getEdit().getMsn());
			obj.setStatus(this.getEdit().getStatus());
			obj.setLevel(this.getEdit().getLevel());
			obj.setOrgId(this.getEdit().getOrgId());
			//设置通用的修改数据属性 修改时间和修改人
			EntityDataUtil<SystemUser,Long> currUtil = new EntityDataUtil<SystemUser,Long>();
			currUtil.setModifyPropertyValue(obj);
			//end
			objService.saveOrUpdate(obj);
		}catch (Exception e) {
			String updateErrorN18 = MessageFactory.getMessage(PlatformConstants.USER_BUNDLE_NAME,"update.data.version.not.same.error.message", FacesMessage.SEVERITY_ERROR).getDetail();
			this.setEditDataInPageFlag(false);
			this.getErrorMessages().add(updateErrorN18);
			return result;
		} finally {
            //do nothing;//关闭session的时候还会报，并且在session那里抓取了所有的Exception。
        }
		return result;
	}
	
	public String preCreateAction(){
		String result = null;
		clearErrorMessages();
		this.setAction(PlatformConstants.ACTION_NEW_TYPE);
		SystemUserVo objVo =new SystemUserVo();
		objVo.setSex("M");
		objVo.setStatus(0);
		objVo.setLevel("1");
		this.setEdit(objVo);
		return result;
	}
	
	public String saveAction(){//create new
		String result = null;
		clearErrorMessages();
		validator(this.getErrorMessages(),this.getEdit());
		if (!(this.getErrorMessages().isEmpty())) {
			return null;
		}
		ISystemUserService<SystemUser,String> objService = (ISystemUserService<SystemUser,String>)SpringFacesUtil.getSpringBean(PlatformSpringBeanConstants.SYSTEM_USER_SERVICE_BEAN_NAME);
		objService.setEntityClass(SystemUser.class);
		objService.setPKClass(String.class);
		if (null != this.getEdit() && !("".equals(this.getEdit().getLoginName())) ) {
			SystemUser theUser = objService.findUniqueBy("loginName", this.getEdit().getLoginName());//
			if (null != theUser) {
				String systemUserExistErrorN18 = MessageFactory.getMessage(PlatformConstants.USER_BUNDLE_NAME,"system.user.loginname.exists.error.message", FacesMessage.SEVERITY_ERROR,this.getEdit().getLoginName()).getDetail();
				this.getErrorMessages().add(systemUserExistErrorN18);
			}
		}
		if (!(this.getErrorMessages().isEmpty())) {
			return null;
		}
		SystemUser newObj = new SystemUser();
		BeanCopier copyHere = BeanCopier.create(SystemUserVo.class, SystemUser.class, false);
		copyHere.copy(this.getEdit(), newObj, null);
		//设置通用的修改数据属性 修改时间和修改人
		try {
			EntityDataUtil<SystemUser,Long> currUtil = new EntityDataUtil<SystemUser,Long>();
			currUtil.setCreatePropertyValue(newObj);
		}catch (Exception e) {
			return result;
		} finally {
            //do nothing;//关闭session的时候还会报，并且在session那里抓取了所有的Exception。
        }
		//end
		objService.save(newObj);
		return result;
	}
	public String refreshPageAction(){
		String result = null;
		this.getPage().getPageDatas();
		return result;
	}
	public String searchPageAction(){
		this.getPage().getPageDatas();
		this.setAction(PlatformConstants.ACTION_SEARCH_TYPE);
		this.setEdit(null);
		this.setView(null);
		return null;
	}
	public String loadUserRoleAction(){
		String result = null;
		String objId= (String) SpringFacesUtil.getRequestParameter("objId");
		String loginName= (String) SpringFacesUtil.getRequestParameter("loginName");
		this.setCurrentUserId(objId);
		this.setCurrentLoginName(loginName);
		//获取已分配的权限值，存入roles
		IUserRoleService<UserRole,String> objService = objService = (IUserRoleService<UserRole,String>)SpringFacesUtil.getSpringBean(PlatformSpringBeanConstants.USER_ROLE_SERVICE_BEAN_NAME);
		objService.setEntityClass(UserRole.class);
		objService.setPKClass(String.class);
		List<UserRole> uRoles = objService.findBy("userId", objId);
		if (null != uRoles){
			String[] tempRoles = new String[uRoles.size()];
			for (int i=0;i<uRoles.size();i++) {
				tempRoles[i] = uRoles.get(i).getRoleId();
			}
			this.setRoles(tempRoles);
		} else {
			this.setRoles(new String[]{""});
		}
		//获取所有的角色
		IAuthorityRoleService<AuthorityRole,String> newObjService = (IAuthorityRoleService<AuthorityRole,String>)SpringFacesUtil.getSpringBean(PlatformSpringBeanConstants.AUTHORITY_ROLE_SERVICE_BEAN_NAME);
		newObjService.setEntityClass(AuthorityRole.class);
		newObjService.setPKClass(String.class);
		List<AuthorityRole> tallRoles = newObjService.getAll("sort", false);
		SelectItem[] tempAllRoles = null;
		if (null != tallRoles) {
			tempAllRoles = new SelectItem[tallRoles.size()];
			for (int j=0;j<tallRoles.size();j++) {
				AuthorityRole role = tallRoles.get(j);
				tempAllRoles[j] =  new SelectItem(role.getId(), role.getName());
			}
		} else {
			tempAllRoles = new SelectItem[]{new SelectItem("", "please ")};
		}
		this.setAllRoles(tempAllRoles);
		return result;
	}
	public String allocateUserRoleAction(){
		String result = null;
		String rolesStr= (String) SpringFacesUtil.getRequestParameter("rolesStr");
		IUserRoleService<UserRole,String> objService = objService = (IUserRoleService<UserRole,String>)SpringFacesUtil.getSpringBean(PlatformSpringBeanConstants.USER_ROLE_SERVICE_BEAN_NAME);
		objService.setEntityClass(UserRole.class);
		objService.setPKClass(String.class);
		//删除当前用户角色关联
		if (null != this.getCurrentUserId() && !("".equals(this.getCurrentUserId()))) {
			List<UserRole> uRoles = objService.findBy("userId", this.getCurrentUserId());
			for (UserRole ur:uRoles) {
				objService.removeById(ur.getId());
			}
		}
		//保存新的用户角色关联
		if (!(rolesStr.isEmpty())) {
			UserRole newObj = null;
			String[] roles = rolesStr.split(",");
			for (int i=0;i<roles.length;i++) {
				if (!(roles[i].isEmpty())) {
					newObj = new UserRole();
					newObj.setUserId(this.getCurrentUserId());
					newObj.setRoleId(roles[i]);
					try {
						EntityDataUtil<UserRole,String> currUtil = new EntityDataUtil<UserRole,String>();
						currUtil.setCreatePropertyValue(newObj);
					}catch (Exception e) {
						return result;
					} finally {
			            //do nothing;//关闭session的时候还会报，并且在session那里抓取了所有的Exception。
			        }
					//save
					objService.save(newObj);
				}
			}
			
		}
		return result;
	}
	private void validator(List<String> errorMessages,SystemUserVo eidt){
		String loginNameLabelN18 = MessageFactory.getMessage(PlatformConstants.USER_BUNDLE_NAME,"system.user.loginname.display", FacesMessage.SEVERITY_ERROR).getDetail();
		ValidatorUtil.EmptyValidatorForInput(errorMessages, edit.getLoginName(), loginNameLabelN18);
		String mobileLabelN18 = MessageFactory.getMessage(PlatformConstants.USER_BUNDLE_NAME,"system.user.mobile.display", FacesMessage.SEVERITY_ERROR).getDetail();
		ValidatorUtil.mobileValidate(errorMessages, mobileLabelN18, edit.getMobile());
		String phoneLabelN18 = MessageFactory.getMessage(PlatformConstants.USER_BUNDLE_NAME,"system.user.phone.display", FacesMessage.SEVERITY_ERROR).getDetail();
		ValidatorUtil.phoneValidate(errorMessages, phoneLabelN18, edit.getPhone());
		String emailLabelN18 = MessageFactory.getMessage(PlatformConstants.USER_BUNDLE_NAME,"system.user.email.display", FacesMessage.SEVERITY_ERROR).getDetail();
		ValidatorUtil.emailValidate(errorMessages, emailLabelN18, edit.getEmail());
	}
}
